package com.yx.pc.api.controller;


import com.lijing.wechatpay.util.PayMD5;
import com.lijing.wechatpay.util.io.IOUtils;
import com.yx.common.utils.R;
import com.yx.modules.api.annotation.AuthIgnore;
import com.yx.modules.api.annotation.LoginUser;
import com.yx.modules.api.entity.TbUser;
import com.yx.modules.api.service.TbUserService;
import com.yx.pay.wxpay.sdk.WXPay;
import com.yx.pay.wxpay.sdk.WXPayUtil;
import com.yx.pay.wxpay.sdk.WxPayCfg;
import com.yx.pay.wxpay.test.WXPayConfigImpl;
import com.yx.pay.wxpay.test.WechatPay;
import com.yx.pay.wxpay.util.EcodeUtil;
import com.yx.system.entity.TdOnlinePayLog;
import com.yx.system.entity.TdOrder;
import com.yx.system.entity.TdWalletPayLog;
import com.yx.system.service.TdOnlinePayLogService;
import com.yx.system.service.TdOrderService;
import com.yx.system.service.TdWalletPayLogService;
import com.yx.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("pc/api/wxpay")
public class wxController {


    @Autowired
    private TdOrderService tdOrderService;

    @Autowired
    private TdOnlinePayLogService tdOnlinePayLogService;

    @Autowired
    private TdWalletPayLogService tdWalletPayLogService;

    @Autowired
    private TbUserService tbUserService;

    /*
    * 下单
    */
    @RequestMapping("/doUnifiedOrder")
    public R doUnifiedOrder(@LoginUser TbUser tbUser, String money, HttpServletRequest request) throws Exception {
        System.out.print("==========================进入微信支付=================================");
        String orderNo = OrderUtil.getOrderNo2();
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("body", "购买商品");
        data.put("out_trade_no", orderNo);
        data.put("fee_type", "CNY");
        data.put("product_id",orderNo);
        data.put("total_fee", money + "");
//        data.put("total_fee", 1+ "");
        data.put("spbill_create_ip", NetWorkUtil.getIpAddress(request));
        data.put("notify_url", "http://www.youwenyuedu.com:8080/youxiang/pc/api/wxpay/notify");
        data.put("trade_type", "NATIVE");
        WxPayCfg config = WXPayConfigImpl.getInstance();
        Map<String, String> r = new HashMap<>();
        WechatPay wechatPay = new WechatPay();
        try {
            WXPay wxPay = new WXPay(config);
            r = wxPay.unifiedOrder(data);
//            for (Object o : r.keySet()) {
//                System.out.println("key=" + o + " value=" + r.get(o));
//                logger.info("key=",o);
//                logger.info(" value=",r.get(o));
//            }
            wechatPay.setAppId("wx83e895bd1ea53c4f");
            wechatPay.setNonceStr(PayMD5.GetMD5nonce_str());
            wechatPay.setSignType("MD5");
            wechatPay.setPrepay_id("prepay_id=" + r.get("prepay_id"));
            wechatPay.setCode_url("code_url=" + r.get("code_url"));
            wechatPay.setTimeStamp(com.lijing.wechatpay.conn.PaymentTools.getTimeStamp());
            String sign = com.lijing.wechatpay.impl.PayImpl.paySign(wechatPay, "F968E8E975723BE7C44DA2057C613860");
            wechatPay.setOut_trade_no(orderNo);
            wechatPay.setPaySign(sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        TdOrder order = new TdOrder();
        order.setUuid(tbUser.getUuid());
        //为订单赋值
        order.setBillno(orderNo);
        order.setBookid(null);
        order.setCreatedate(new Date());
        order.setTotalfee(Integer.parseInt(money));
        order.setUsername(tbUser.getNickname());
        order.setUserphone(tbUser.getMobile());
        order.setSectionid(null);
        order.setOrderstatus(PayStatus.unpaid.getName());
        order.setIspay(false);
        order.setPaytype(PayType.WX_SCAN.getName());
        order.setCreateuser(tbUser.getUsername());
        order.setYear(DateUtil.getYear(new Date()));
        order.setMonth(DateUtil.getMonth(new Date()));
        order.setDay(DateUtil.getDay(new Date()));
        tdOrderService.insert(order);
        //存入支付数据
        TdOnlinePayLog opl = new TdOnlinePayLog();
        opl.setBalance(tbUser.getBalance()+(order.getTotalfee()*100));
        opl.setCreatedate(new Date());
        opl.setBillno(orderNo);
        opl.setCreateuser(tbUser.getUsername());
        opl.setUuid(UUIDUtil.getUUID());
        opl.setUserid(tbUser.getUserId() + "");
        opl.setPaytype(order.getPaytype());
        opl.setTitle("余额充值");
        opl.setTotalfee(order.getTotalfee());
        opl.setPaystatus(PayStatus.unpaid.getName());
        opl.setWebhookstatus(PayStatus.unpaid.getName());
        opl.setUserpaystatus(PayType.WX_SCAN.getName());
        tdOnlinePayLogService.insert(opl);

        TdWalletPayLog twp = new TdWalletPayLog();
        twp.setBillno(orderNo);
        twp.setCreatedate(new Date());
        twp.setCreateuser(tbUser.getUsername());
        twp.setPaystatus(PayStatus.unpaid.getName());
        twp.setReturntype(PayStatus.unpaid.getName());
        twp.setTitle("余额充值");
        twp.setTotalfee(Integer.parseInt(money));
        twp.setUserpaystatus("WX_SCAN");
        twp.setPaytype("put");
        twp.setUuid(tbUser.getUuid());
        twp.setWebhookstatus(PayStatus.unpaid.getName());
        tdWalletPayLogService.insert(twp);
        return R.ok().put("data", wechatPay);
    }

    /**
     * 回调
     *
     * @return
     */
    @AuthIgnore
    @RequestMapping("/notify")
    public R notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //接收xml数据
        String respXML = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        //验证签名
        WXPayConfigImpl config = WXPayConfigImpl.getInstance();

        System.out.println("==============================================="+WXPayUtil.isSignatureValid(respXML, config.getKey()));
        if (WXPayUtil.isSignatureValid(respXML, config.getKey())) {
            //解析xml为map
            Map<String, String> map = WXPayUtil.xmlToMap(respXML);
//            for (Object o : result.keySet()) {
//                System.out.println("key=" + o + " value=" + result.get(o));
//                logger.info("key=",o);
//                logger.info(" value=",result.get(o));
//            }
            //下面是 业务逻辑处理
            String orderNo = map.get("out_trade_no").toString();
            int totalFee = Integer.parseInt(map.get("total_fee").toString());
            TdOrder tdOrder = tdOrderService.queryByBillNo(orderNo);
            System.out.println("==============================================="+tdOrder.getIspay());
            if (tdOrder.getIspay()) {
                return R.ok().put("return_code", "SUCCESS");
            }
            if (tdOrder == null) {
                return R.error("未查询到订单信息!");
            }
            if (map.get("return_code").equals("FAIL")) {
                return R.ok().put("return_code", "FAIL").put("return_msg", "交易失败：" + map.get("return_msg"));
            }
           System.out.println(tdOrder.getTotalfee().intValue());
            System.out.println(Integer.parseInt(map.get("total_fee").toString()));
            if (tdOrder.getTotalfee().intValue() != totalFee) {
                return R.ok().put("return_code", "FAIL").put("return_msg", "订单金额不一致！");
            }
            System.out.println("=====================================正常执行逻辑代码==============================");
            //修改订单状态
            tdOrder.setIspay(true);
            tdOrder.setPaydate(new Date());
            tdOrder.setOrderstatus(PayStatus.success.getName());
            tdOrder.setUpdatedate(new Date());
            tdOrder.setUpdateuser("sys");
            tdOrderService.updateByPrimaryKey(tdOrder);

            TdOnlinePayLog tdOnlinePayLog = tdOnlinePayLogService.queryByBillNo(orderNo);
            TdWalletPayLog tdWalletPayLog = tdWalletPayLogService.queryByBillNo(orderNo);

            tdOnlinePayLog.setWebhookstatus(PayStatus.success.getName());
            tdOnlinePayLog.setPaystatus(PayStatus.success.getName());
            tdOnlinePayLog.setReturntype("notify_url");
            tdOnlinePayLog.setUpdatedate(new Date());
            tdOnlinePayLog.setUpdateuser("sys");
            tdOnlinePayLogService.updateByPrimaryKey(tdOnlinePayLog);

            tdWalletPayLog.setWebhookstatus(PayStatus.success.getName());
            tdWalletPayLog.setReturntype("notify_url");
            tdWalletPayLog.setPaystatus(PayStatus.success.getName());
            tdWalletPayLog.setUpdatedate(new Date());
            tdWalletPayLog.setUpdateuser("sys");
            tdWalletPayLogService.updateByPrimaryKey(tdWalletPayLog);
            //增加用户余额
            TbUser tbUser = tbUserService.queryByUid(tdOrder.getUuid());
            tbUser.setBalance(tbUser.getBalance() + totalFee*100);
            tbUserService.update(tbUser);
        }else {
            return R.error().put("return_code", "FAIL").put("return_msg", respXML);
        }
        return R.ok().put("return_code", "SUCCESS");
    }

    /*
    * 实时查询订单状态
    */
    @RequestMapping("query")
    public R query(String orderNo){
        TdOrder tdOrder = tdOrderService.queryByBillNo(orderNo);
        System.out.println("==========================="+tdOrder.getOrderstatus()+"===============================");
        System.out.println("=================================="+tdOrder.getOrderstatus().equals("success")+"====================================================");
        if (tdOrder.getIspay() && tdOrder.getOrderstatus().equals("success")){
            System.out.println("支付成功");
            return R.ok().put("result",1);
        }else {
            System.out.println("支付失败");
            return R.ok().put("result",0);
        }
    }
}
